package com.example.basic.interceptor;

import com.example.basic.domain.Games;
import com.example.basic.exception.CustomException;
import com.example.basic.handler.CachedBodyHttpServletRequest;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class MyInterceptor implements HandlerInterceptor {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getContentType() != null && request.getContentType().contains("application/json")) {
            CachedBodyHttpServletRequest wrappedRequest = new CachedBodyHttpServletRequest(request);
            String requestBody = wrappedRequest.getReader().lines().reduce("", String::concat);
            System.out.println("请求体 JSON 字符串: " + requestBody);

            // 将 JSON 转换为 Java 对象
            try {
                Games myRequestBody = objectMapper.readValue(requestBody, Games.class);
                System.out.println("转换后的 Java 对象: " + myRequestBody);
            } catch (Exception e) {
                throw new CustomException("500", "请求体格式异常，请检查");
            }

            return true;
        }
        return true;
    }
}

